iT邦幫忙

2024 iThome 鐵人賽

DAY 23
1
佛心分享-刷題不只是刷題

8月 LeetCode Daily 見聞錄系列 第 23

[8/23] 592. Fraction Addition and Subtraction

  • 分享至 

  • xImage
  •  

Medium
Related Topics: Math / String / Simulation
LeetCode Source

解題想法

首先我們要定義分子跟分母為01

之後在尋訪時依照以下步驟

我們在分子的部份

當前遇到分數之分子乘以目前加總之分母

加上

當前遇到分數之分母乘以目前加總之分子

在分母的部份直接乘以當前遇到之分母

之後就是找尋加總分子跟分母的最大公因數

然後將當前加總分子跟分母除以最大公因數

最後回傳字串分子 + "/" + 分母

Complexity

Time Complexity: O(n)
Space Complexity: O(1)

Python

class Solution:
    def fractionAddition(self, expression: str) -> str:
        up, down = 0, 1

        i = 0

        while i < len(expression):
            sign = 1
            if expression[i] == '-':
                sign = -1
                i += 1
            elif expression[i] == '+':
                i += 1

            up_num = 0

            while i < len(expression) and expression[i].isdigit():
                up_num = up_num * 10 + int(expression[i])
                i += 1

            up_num *= sign
            i+= 1

            down_num = 0

            while i < len(expression) and expression[i].isdigit():
                down_num = down_num * 10 + int(expression[i])
                i += 1

            up = up * down_num + up_num * down
            down *= down_num

            if up == 0:
                down = 1    
            else:
                ccc = gcd(abs(up), down)
                up //= ccc
                down //= ccc

        return f"{up}/{down}"

C++

class Solution {
public:
    string fractionAddition(string expression) {
        std::istringstream iss (expression);
        int up = 0, down = 1, n_up, n_down;
        char dummy;
        while (iss >> n_up >> dummy >> n_down) {
            up = up * n_down + n_up * down;
            down *= n_down;
            int gcd = std::gcd(abs(up), down);
            up /= gcd;
            down /= gcd;
        }

        string res = "";

        res += to_string(up);
        res += "/";
        res += to_string(down);

        return res;
    }
};

上一篇
[8/22] 476. Number Complement
下一篇
[8/24] 564. Find the Closest Palindrome
系列文
8月 LeetCode Daily 見聞錄30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言